<template>
  <div style="padding: 20px">
    <a-row :gutter="16">
      <a-col :span="6">
        <a-card title="总体数据" :bordered="false" class="stat-card">
          <div class="card-content">
            <p class="total-value">{{ attendanceStats.total?.actualCheckins || 0 }}/{{ attendanceStats.total?.theoreticalCheckins || 0 }}</p>
            <p class="total-desc">实际打卡/理论打卡</p>
            <p class="rate-value">
              <span class="rate-number">{{ attendanceStats.total?.attendanceRate || '0%' }}</span>
              <span class="rate-label">打卡率</span>
            </p>
          </div>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card title="季度数据" :bordered="false" class="stat-card">
          <div class="card-content">
            <p class="total-value">{{ attendanceStats.quarter?.actualCheckins || 0 }}/{{ attendanceStats.quarter?.theoreticalCheckins || 0 }}</p>
            <p class="total-desc">实际打卡/理论打卡</p>
            <p class="rate-value">
              <span class="rate-number">{{ attendanceStats.quarter?.attendanceRate || '0%' }}</span>
              <span class="rate-label">打卡率</span>
            </p>
          </div>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card title="月度数据" :bordered="false" class="stat-card">
          <div class="card-content">
            <p class="total-value">{{ attendanceStats.month?.actualCheckins || 0 }}/{{ attendanceStats.month?.theoreticalCheckins || 0 }}</p>
            <p class="total-desc">实际打卡/理论打卡</p>
            <p class="rate-value">
              <span class="rate-number">{{ attendanceStats.month?.attendanceRate || '0%' }}</span>
              <span class="rate-label">打卡率</span>
            </p>
          </div>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card title="周度数据" :bordered="false" class="stat-card">
          <div class="card-content">
            <p class="total-value">{{ attendanceStats.week?.actualCheckins || 0 }}/{{ attendanceStats.week?.theoreticalCheckins || 0 }}</p>
            <p class="total-desc">实际打卡/理论打卡</p>
            <p class="rate-value">
              <span class="rate-number">{{ attendanceStats.week?.attendanceRate || '0%' }}</span>
              <span class="rate-label">打卡率</span>
            </p>
          </div>
        </a-card>
      </a-col>
    </a-row>
  </div>

  <DynamicTable
    header-title="学生列表"
    :data-request="loadStudentData"
    :columns="columns"
    :form-props="{ colon: false }"
  >
    <template #toolbar>
      <a-button
        :icon="h(PlusOutlined)"
        @click="openStudentModal({})"
      >
        新增
      </a-button>
    </template>
  </DynamicTable>
</template>

<script lang="tsx" setup>
import { h, onMounted, ref } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { message, Tag } from 'ant-design-vue';
import type { TableColumn } from '@/components/core/dynamic-table';
import { useTable } from '@/components/core/dynamic-table';
import { useFormModal } from '@/hooks/useModal/';
import { Api } from '@/api/';
import type { CustomRenderParams } from '@/components/core/dynamic-table';
import { useRouter } from 'vue-router';
import { request } from '@/utils/request';

// 学生类型和状态枚举（根据后端定义调整）
const studentTypeMap = {
  1: '线上',
  2: '线下',
};
const statusMap = {
  0: '已停用',
  1: '学习中',
  2: '待续费',
  4: '已毕业',
};

// 定义数据类型
export interface StudentItem {
  id: number;
  student_id: string; // 学员ID
  phone: string;
  userName: string;
  teacherName?: string; // 带班老师
  className?: string; // 所在班级
  checkinDays?: number; // 总打卡次数
  checkinRate?: string | number; // 打卡率
  studentType: number;
  status: number;
  startAt: string; // 入学时间
  expireAt: string;
  createdAt: string;
  updatedAt: string;
}

// 初始化表格
const [DynamicTable, tableInstance] = useTable({
  pagination: { defaultPageSize: 10, showSizeChanger: true },
  size: 'small',
  rowKey: 'id',
  bordered: true,
});

// 表单弹窗
const [showModal] = useFormModal();

// 新增/编辑
const openStudentModal = async (record: Partial<StudentItem>) => {
  const [formRef] = await showModal({
    modalProps: {
      title: record.id ? '编辑学生' : '新增学生',
      width: 700,
      onFinish: async (values) => {
        if (record.id) {
          await Api.manageStudent.studentUpdate({ id: record.id }, values);
        } else {
          await Api.manageStudent.studentCreate(values);
        }
        tableInstance.reload();
      },
    },
    formProps: {
      labelWidth: 100,
      schemas: [
        { field: 'userName', component: 'Input', label: '姓名', rules: [{ required: true }] },
        { field: 'phone', component: 'Input', label: '手机号', rules: [{ required: true }] },
        { field: 'studentType', component: 'Select', label: '学习方式', componentProps: { options: Object.entries(studentTypeMap).map(([v, l]) => ({ label: l, value: Number(v) })) }, rules: [{ required: true }] },
        { field: 'status', component: 'Select', label: '状态', componentProps: { options: Object.entries(statusMap).map(([v, l]) => ({ label: l, value: Number(v) })) } },
        { field: 'startAt', component: 'DatePicker', label: '开始时间', componentProps: { showTime: true, style: { width: '100%' } }, rules: [{ required: true }] },
        { field: 'expireAt', component: 'DatePicker', label: '结束时间', componentProps: { showTime: true, style: { width: '100%' } }, rules: [{ required: true }] },
      ],
    },
  });
  formRef?.setFieldsValue(record);
};

// 删除
const delConfirm = async (record: StudentItem) => {
  await Api.manageStudent.studentRemove({ id: record.id });
  tableInstance.reload();
};

// 渲染
const renderTag = (text: string, color: string) => <Tag color={color}>{text}</Tag>;

// 列定义
const columns: TableColumn<StudentItem>[] = [
  { 
    title: '学员ID', 
    dataIndex: 'student_id', 
    width: 120,
    hideInSearch: true,
    customRender: ({ record }) => {
      // 确保能够显示student_id，无论是哪种格式
      return record.student_id || (record.studentId ? record.studentId : '-');
    }
  },
  { 
    title: '姓名', 
    dataIndex: 'userName', 
    width: 100,
    formItemProps: {
      label: '',
      componentProps: {
        placeholder: '搜索学员'
      }
    }
  },
  { title: '手机号', dataIndex: 'phone', width: 120, hideInSearch: true },
  { 
    title: '带班老师', 
    dataIndex: 'teacherName', 
    width: 120, 
    hideInSearch: true,
    customRender: ({ record }) => {
      // 如果有rawClasses数据，处理老师显示
      if (record.rawClasses && record.rawClasses.length > 0) {
        // 提取所有不同的老师名字
        const allTeachers = [...new Set(record.rawClasses.map(cls => cls.teacherName))];
        
        if (allTeachers.length === 1) {
          // 只有一个老师，直接显示
          return allTeachers[0] || '-';
        } else {
          // 有多个老师，最多显示两个
          const displayTeachers = allTeachers.slice(0, 2).join('、');
          
          // 如果超过两个，添加悬浮提示
          if (allTeachers.length > 2) {
            return (
              <a-tooltip title={allTeachers.join('、')}>
                <span>
                  {displayTeachers}
                  <span style="color: #999; font-size: 12px; margin-left: 4px;">
                    等{allTeachers.length}位老师
                  </span>
                </span>
              </a-tooltip>
            );
          }
          
          return displayTeachers;
        }
      }
      
      // 如果没有班级数据但有teacherName字段，使用该字段
      return record.teacherName || '-';
    }
  },
  { 
    title: '所在班级', 
    dataIndex: 'className', 
    width: 150, 
    hideInSearch: true,
    customRender: ({ record }) => {
      // 如果有rawClasses数据，处理班级显示
      if (record.rawClasses && record.rawClasses.length > 0) {
        if (record.rawClasses.length === 1) {
          // 只有一个班级，直接显示
          return record.rawClasses[0].className;
        } else {
          // 有多个班级，最多显示两个
          const displayClassNames = record.rawClasses.slice(0, 2).map(cls => cls.className).join('、');
          
          // 如果超过两个，添加"等x个班级"的提示
          if (record.rawClasses.length > 2) {
            const allClassNames = record.rawClasses.map(cls => cls.className).join('、');
            
            return (
              <a-tooltip title={allClassNames}>
                <span>
                  {displayClassNames}
                  <span style="color: #999; font-size: 12px; margin-left: 4px;">
                    等{record.rawClasses.length}个班级
                  </span>
                </span>
              </a-tooltip>
            );
          }
          
          return displayClassNames;
        }
      }
      return '未分班';
    }
  },
  { 
    title: '总打卡次数', 
    dataIndex: 'checkinDays', 
    width: 100, 
    hideInSearch: true,
    customRender: ({ record }) => {
      return record.checkinDays || 0;
    }
  },
  { 
    title: '打卡率', 
    dataIndex: 'checkinRate', 
    width: 100, 
    hideInSearch: true,
    customRender: ({ record }) => {
      if (!record.checkinRate) return '0%';
      const rate = typeof record.checkinRate === 'string' 
        ? record.checkinRate 
        : `${record.checkinRate}%`;
      return <a-progress percent={parseFloat(rate)} size="small" />;
    }
  },
  { 
    title: '入学时间', 
    dataIndex: 'createdAt', 
    width: 120, 
    hideInSearch: true,
    customRender: ({ record }) => {
      // 从rawClasses中获取第一个班级的joinAt
      if (record.rawClasses && record.rawClasses.length > 0 && record.rawClasses[0].joinAt) {
        return new Date(record.rawClasses[0].joinAt).toLocaleDateString();
      }
      
      // 如果没有rawClasses但有createdAt，使用该字段
      if (record.createdAt) {
        return new Date(record.createdAt).toLocaleDateString();
      }
      
      return '-';
    }
  },
  { 
    title: '当周平均打卡', 
    dataIndex: 'weeklyAverageCheckin', 
    width: 120, 
    hideInSearch: true,
    customRender: ({ record }) => {
      // 使用学生的当周平均打卡数据
      const value = record.weeklyAverageCheckin || 0;
      // 将小数转换为百分比格式
      return `${(value * 100).toFixed(0)}%`;
    }
  },
  { 
    title: '当月平均打卡', 
    dataIndex: 'monthlyAverageCheckin', 
    width: 120, 
    hideInSearch: true,
    customRender: ({ record }) => {
      // 使用学生的当月平均打卡数据
      const value = record.monthlyAverageCheckin || 0;
      // 将小数转换为百分比格式
      return `${(value * 100).toFixed(0)}%`;
    }
  },
  {
    title: '操作', 
    dataIndex: 'action', 
    hideInSearch: true, 
    fixed: 'right', 
    width: 170,
    customRender: ({ record }) => (
      <div style="display: flex; gap: 8px;">
        <a-button 
          type="primary" 
          ghost 
          size="small"
          style="color: #5E50F9; border-color: #5E50F9"
          onClick={() => assignClass(record)}
        >
          分班
        </a-button>
        <a-button 
          ghost 
          size="small"
          style="color: #666; border-color: #d9d9d9"
          onClick={() => viewStudentDetails(record)}
        >
          查看详情
        </a-button>
      </div>
    )
  },
];

const router = useRouter();

const viewStudentDetails = (record) => {
  router.push({ 
    name: 'StudentDetail', // 确保这里的路由名称与 class-detail.vue 中的路由名称一致
    params: { studentId: record.id } // 传递学生的 ID 作为参数
  });
};

const assignClass = async (record) => {
  const [formRef] = await showModal({
    modalProps: {
      title: '分配班级',
      width: 500,
      onFinish: async (values) => {
        try {
          // 构造请求参数
          const params = {
            studentId: record.id,
            classId: values.classId,
            // 自动使用当前时间作为加入班级时间
            joinAt: new Date().toISOString()
          };
          
          // 调用正确的API将学生分配到指定班级
          await Api.manageStudent.studentAddStudentToClass(params);
          message.success('分班成功');
          tableInstance.reload();
        } catch (error) {
          console.error('分班失败', error);
          message.error('分班失败，请重试');
        }
      },
    },
    formProps: {
      labelWidth: 100,
      schemas: [
        {
          field: 'classId',
          component: 'Select',
          label: '选择班级',
          componentProps: {
            request: async () => {
              try {
                // 获取班级列表
                const result = await Api.manageClass.classFindAll({});
                if (!result || !result.items) return [];
                
                // 转换为下拉选项格式
                return result.items.map(cls => ({
                  label: cls.className,
                  value: cls.id,
                  disabled: cls.status !== 1 // 假设状态1为活跃班级
                }));
              } catch (error) {
                console.error('获取班级列表失败', error);
                return [];
              }
            },
            placeholder: '请选择要分配的班级',
            allowClear: false, // 不允许清除选择
            showSearch: true,
            optionFilterProp: 'label',
            style: { width: '100%' }
          },
          rules: [
            { 
              required: true, 
              message: '请选择班级',
              validator: (rule, value) => {
                console.log('班级选择验证:', value);
                if (value) {
                  return Promise.resolve();
                }
                return Promise.reject('请选择班级');
              }
            }
          ]
        }
      ],
    },
  });
};

const loadStudentData = async (params = {}) => {
  try {
    console.log('开始请求学生列表数据，请求参数:', params);
    // 使用新的API接口获取包含班级信息的学生列表
    const result = await request('/api/manage/admin/manage/student/with-class-info', {
      method: 'GET'
    });
    
    console.log('【学生列表原始数据】:', JSON.stringify(result, null, 2));
    
    if (result && Array.isArray(result)) {
      // 转换数据结构以匹配表格期望的格式
      const transformedItems = result.map(student => {
        // 确保rawClasses存在，如果后端直接返回了classes数组，使用它
        const rawClasses = student.rawClasses || student.classes || [];
        
        // 确保student_id字段存在
        const studentId = student.student_id || student.studentId || '';
        
        console.log('处理学生数据:', student.id, studentId);
        
        // 直接使用后端返回的字段，避免二次赋值产生的问题
        return {
          id: student.id,
          student_id: studentId, 
          studentId: studentId, // 同时保留studentId字段
          phone: student.phone,
          userName: student.userName,
          teacherName: student.teacherName,
          className: student.className,
          checkinDays: student.checkinDays,
          checkinRate: student.checkinRate,
          // 使用rawClasses中第一个班级的joinAt作为入学时间
          createdAt: rawClasses.length > 0 ? rawClasses[0].joinAt : null,
          weeklyAverageCheckin: student.weeklyAverageCheckin,
          monthlyAverageCheckin: student.monthlyAverageCheckin,
          // 保存rawClasses数据供渲染使用
          rawClasses: rawClasses
        };
      });
      
      console.log('转换后的学生列表数据示例(第一条学生ID):', 
        transformedItems.length > 0 ? transformedItems[0].student_id : '无数据');
      console.log('学生总数:', transformedItems.length);
      
      // 返回转换后的数据
      return {
        items: transformedItems,
        total: transformedItems.length
      };
    }
    
    console.log('API返回数据格式异常，没有获取到学生列表数据');
    return { items: [], total: 0 };
  } catch (error) {
    console.error('获取学生列表失败，错误详情:', error);
    return { items: [], total: 0 };
  }
};

// 打卡统计数据
const attendanceStats = ref({
  totalStudents: 0,
  totalClasses: 0,
  total: { actualCheckins: 0, theoreticalCheckins: 0, attendanceRate: '0%' },
  quarter: { actualCheckins: 0, theoreticalCheckins: 0, attendanceRate: '0%' },
  month: { actualCheckins: 0, theoreticalCheckins: 0, attendanceRate: '0%' },
  week: { actualCheckins: 0, theoreticalCheckins: 0, attendanceRate: '0%' }
});

// 获取打卡统计数据
const fetchAttendanceStats = async () => {
  try {
    console.log('开始请求学生打卡统计数据');
    // 使用正确的API接口路径
    const result = await request('/api/manage/admin/manage/student/statistics/attendance', {
      method: 'GET'
    });
    console.log('【学生打卡统计数据】:', JSON.stringify(result, null, 2));
    attendanceStats.value = result;
  } catch (error) {
    console.error('获取学生打卡统计数据失败，错误详情:', error);
  }
};

// 组件挂载时获取新的打卡统计数据
onMounted(() => {
  fetchAttendanceStats();
});
</script>

<style scoped lang="less">
.stat-card {
  transition: all 0.3s ease;
  
  .card-content {
    transition: all 0.3s ease;
  }
  
  .total-value {
    font-size: 30px;
    font-weight: bold;
    margin-bottom: 4px;
    line-height: 1.2;
  }
  
  .total-desc {
    font-size: 13px;
    color: #999;
    margin-bottom: 16px;
  }
  
  .rate-value {
    .rate-number {
      font-size: 20px;
      font-weight: bold;
      margin-right: 4px;
    }
    
    .rate-label {
      font-size: 13px;
      color: #999;
    }
  }
  
  &:hover {
    background-color: #4c46e5;
    
    :deep(.ant-card-head) {
      color: white;
      background-color: #4c46e5;
      border-bottom-color: rgba(255, 255, 255, 0.2);
    }
    
    .card-content {
      color: white;
    }
    
    .total-desc, .rate-label {
      color: rgba(255, 255, 255, 0.7);
    }
  }
}
</style>
